<template>
  <div class="myContainer">
    <el-row class="myBorderBottom myMarginBottom_10px">
      <el-col :span="7" class="myTitleText">计划基本信息</el-col>
    </el-row>

    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        例行计划名称 :
      </el-col>
      <el-col :span="6">
        <el-input placeholder="计划名称" v-model="plan_title" :readonly="readonly"></el-input>
      </el-col>
    </el-row> 

    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        使用模板 :
      </el-col>
      <el-col :span="6">
        <template>
          <el-select v-model="template_id"
            clearable
            :disabled="readonly"
            placeholder="请选择模板">
            <el-option
              v-for="item in template"
              :key="item.template_name"
              :label="item.template_name"
              :value="item.template_id">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>

    <!-- <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划监察人 :
      </el-col>
      <el-col :span="6">
        <el-input placeholder="计划监察人" v-model="plan_pop" :disabled="readonly" @focus="showRole"></el-input>
      </el-col>
    </el-row> -->

    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        抽检项完成率 :
      </el-col>
      <el-col :span="6">
        <el-input placeholder="抽检项完成率" v-model="finish_rate" :readonly="readonly"></el-input>
      </el-col>
      <el-col :span="2" class="myLineHeight_40px">
        %
      </el-col>
    </el-row>
  
    <el-row class="myBorderBottom myMarginBottom_10px">
      <el-col :span="7" class="myTitleText">执行范围</el-col>
    </el-row>

    <!-- <el-row :gutter="10">
      <el-col :span="3" class="myLeftMsg">
        随机选中 :
      </el-col>
      <el-col :span="6">
        <el-slider v-model="sliderValue"></el-slider> 
      </el-col> 
      <el-col :span="3">
        <el-button type="primary" @click="test">执行</el-button>
      </el-col>
    </el-row> -->
    
    <el-row :gutter="10"> 
      <el-col :span="6" :offset="3">
        <el-tree
          :data="treeData"
          show-checkbox
          node-key="value"
          ref="region"
          :props="defaultProps"
          @check-change="getAreaInfo"
          :default-expanded-keys="[]"
          :default-checked-keys="[]">
        </el-tree>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="myMarginBottom_10px"> 
      <el-col :span="6" class="myLineHeight_40px" :offset="3">
        总项目数：{{totalNum}}; 
        已选中：{{checkNum}};
        占比：{{proportionNum}};
      </el-col> 
    </el-row>

    <el-row class="myBorderBottom myMarginBottom_10px">
      <el-col :span="7" class="myTitleText">任务的生成周期及执行期限</el-col>
    </el-row>
    
    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划类型 :
      </el-col>
      <el-col :span="6">
        <template>
          <el-select v-model="gen_type"
            clearable
            :disabled="readonly||disabled" 
            @change="changeType"
            placeholder="请选择计划类型">
            <el-option
              v-for="item in task"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        周期 :
      </el-col>
      <el-col :span="6">
        <el-input placeholder="周期(天)" v-model="plan_cycle" :readonly="readonly" :disabled="gen_type==0"></el-input>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        执行期限 :
      </el-col>
      <el-col :span="6">
        <el-input placeholder="执行期限(天)" v-model="deadline" :readonly="readonly"></el-input>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        初次生效日期 :
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="first_date"
          type="date"
          :editable=false  
          :disabled="readonly||checked"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          placeholder="选择初次生效日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-col>
      <el-col :span="4" class="myLineHeight_40px">
        <template>
          <el-checkbox v-model="checked" @change="checkedChange" :disabled="readonly||!gen_type==0">立即执行</el-checkbox>
        </template>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="myMarginBottom_10px">
      <el-col :span="6" :offset="3">
        <el-button type="primary" v-if="type=='add'" @click="add">新增</el-button>
        <el-button type="primary" v-if="type=='update'" @click="update">保存</el-button>
        <el-button @click="back">返回</el-button>
      </el-col>
    </el-row>
    
    <!--计划监察人角色职务弹出框 start-->
    <el-dialog title="计划监察人角色/职务" class="myRoleDialog" :visible.sync="newRoleDialogVisible">
      <div>
        <el-input placeholder="输入关键字进行搜索" v-model="kw" class="input-with-select">
          <el-button type="primary" slot="append" class="el-icon-search"></el-button>
        </el-input>
      </div>
      <div class="mymarginTop_10px myOV_y_400px">
        <el-tree 
          ref="roleData"
          v-loading="roleDataListLoading"
          :data="roleDataList"
          node-key="role_id"
          :props="RoleDataProps"
          :filter-node-method="filterNode"
          show-checkbox>
          </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="setDeptRoleInfo">提 交</el-button>
        <el-button @click="newRoleDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--计划监察人角色职务弹出框 end-->
  </div>
</template>     
  
<style scoped>
  .myBorderBottom{
    border-bottom:1px dotted #dbdbdb;
    padding-bottom: 5px;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myTitleText{
    font-weight: 500;
    font-size: 16px;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myPaddingTop_10px{
    padding-top: 10px;
  }  
  .myred{
    color: #f00;
    font-size: 12px;
  }
  .myMarginBottom_10px{
    margin-bottom: 10px;
  }
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
  }
  .myVA_M{
    vertical-align: middle;
  }
  .mymarginTop_10px{
    margin-top: 10px;
  }
  .myOV_y_400px{
    max-height: 400px;
    min-height: 200px;
    overflow-y:scroll;
    border: 1px solid #d1dbe5;
  }
</style>

<script>
  import { getAreaTree } from '@/api/area';
  import { addPlan , getTemplateList , infoPlan , updatePlan , createTask } from '@/api/quality';
  import { getRoleList } from '@/api/role';
  export default {
    data(){
      return{
        title:"计划详细",
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now();
          }
        },
        type:"",
        id:"",
        readonly:false,
        radio:1, 
        template_id:"",
        template:[],
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        gen_type:"",
        task:[
          {label:"周期性",value:1},
          {label:"临时性",value:0}
        ], 
        sliderValue:0,
        totalNum:0,
        checkNum:0,
        proportionNum:0,
        deadline:"",
        finish_rate:"",
        first_date:"",
        plan_cycle:"",
        plan_title:"",
        areaid:"",
        areaname:"",
        gen_type:"",
        iszq:true,
        newList:[],
        checked:false,
        default_first_date:"",
        disabled:false,
        newRoleDialogVisible:false,
        plan_pop:"",
        roleDataList:[],
        kw:"",
        roleDataListLoading:false,
        RoleDataProps: {
          label: 'role_name'
        },
        plan_pop_id:""
      }
    },
    components: {
    },
    created(){
      this.type=this.$route.query.type;
      this.id=this.$route.query.id;
      this.ongetAreaTree(); 
      this.ongetTemplateList();
      if(this.type=="add"){
        document.title="新增计划";
      }else if(this.type=="info"){
        this.readonly=true; 
      }else if(this.type=="update"){
        document.title="编辑计划";
        this.readonly=false; 
        this.disabled=true;
      }
    },
    computed: {
    },
    watch: {
      kw(val) {
        this.$refs.roleData.filter(val);
      }
    },
    methods:{
      filterNode(value, data) {
        if (!value) return true;
        return data.role_name.indexOf(value) !== -1;
      },
      add(){
        let vm=this;
        let params={
          "area_range": vm.areaid,
          "deadline": Number(vm.deadline),
          "finish_rate": Number(vm.finish_rate).toFixed(2),
          "first_date": vm.first_date,
          "gen_type": vm.gen_type,
          "plan_cycle": Number(vm.plan_cycle),
          "plan_title": vm.plan_title,
          "template_id": vm.template_id
        } 
        if(vm.checkNum<=0){
          vm.$message.info("执行范围最少为一个小区！");
          return;
        }
        if(vm.gen_type==1 && (Number(vm.deadline)>Number(vm.plan_cycle))){
          vm.$message.info("选择周期性任务时期限不能超过周期！");
          return;
        } 
        if(vm.checked){
          vm.$confirm(`是否立即创建 [ ${vm.plan_title} ] 内的任务？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            addPlan(params).then(response => {
              let res=response.data;
              vm.$message.success("计划创建成功！");
              if(res.data_id){
                createTask(res.data_id).then(response => {
                  vm.$message.success("任务创建成功！");
                  vm.back();
                }).catch(error => {
                  vm.$message.error("任务创建失败！"+error.response.data.error_msg);
                })
              }
            }).catch(error => {
              vm.$message.error("计划创建失败！"+error.response.data.error_msg);
            })
          }).catch(() => {});
        }else{
          addPlan(params).then(response => {
            vm.$message.success("计划创建成功！");
            vm.back();
          }).catch(error => {
            vm.$message.error("执行失败！"+error.response.data.error_msg);
          })
        }
      },
      update(){
        let vm=this;
        let params={
          "area_range": vm.areaid,
          "deadline": Number(vm.deadline),
          "finish_rate": Number(vm.finish_rate).toFixed(2),
          "first_date": vm.first_date,
          "gen_type": vm.gen_type,
          "plan_cycle": Number(vm.plan_cycle),
          "plan_title": vm.plan_title,
          "template_id": vm.template_id
        } 
        if(vm.checkNum<=0){
          vm.$message.info("执行范围最少为一个小区！");
          return;
        }
        if(vm.gen_type==1 && (Number(vm.deadline)>Number(vm.plan_cycle))){
          vm.$message.info("选择周期性任务时期限不能超过周期！");
          return;
        } 
        if(vm.checked){
          vm.$confirm(`是否立即创建 [ ${vm.plan_title} ] 内的任务？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            updatePlan(params,vm.id).then(response => {
              vm.$message.success("计划修改成功！");
              createTask(vm.id).then(response => {
                vm.$message.success("任务创建成功！");
                vm.back();
              }).catch(error => {
                vm.$message.error("任务创建失败！"+error.response.data.error_msg);
              })
            }).catch(error => {
              vm.$message.error("计划修改失败！"+error.response.data.error_msg);
            })
          }).catch(() => {});
        }else{
          updatePlan(params,vm.id).then(response => {
            vm.$message.success("计划修改成功！");
            vm.back();
          }).catch(error => {
            vm.$message.error("计划修改失败！"+error.response.data.error_msg);
          })
        }
      },
      back(){
        this.$router.go(-1);
      }, 
      ongetTemplateList(){
        let vm=this;
        let params={ 
          page_num:1,
          page_size:10000
        } 
        getTemplateList(params).then(response => {
          let res=response.data;
          vm.template=res.rows; 
        }).catch(error => { 
          vm.$message.error("执行失败！"+error.response.data.error_msg);
        })
      },
      getAreaInfo(){
        let vm=this;
        let areas=vm.$refs.region.getCheckedNodes();
        let areaids="",areanames="",num=0;
        for(let i=0; i<areas.length; i++){
          if(areas[i].level==3){
            areaids+=areas[i].value+',';
            areanames+=areas[i].label+',';
            num++;
          }
        }
        vm.areaname=areanames.substring(0,areanames.length-1);
        vm.areaid=areaids.substring(0,areaids.length-1); 
        vm.checkNum=num;
        vm.proportionNum=((num/vm.totalNum)*100).toFixed(2)+'%';
      },
      ongetAreaTree(){
        let vm=this;
        getAreaTree().then(response => {
          let res=response.data;
          let num=0;
          vm.treeData=res; 
          for(let i=0; i<res.length; i++){
            vm.onGetArr(res[i]);
          }
          for(let i=0; i<vm.newList.length; i++){
            if(vm.newList[i].level==3){
              num++;
            }
          }
          vm.totalNum=num; 
          if(vm.type=='info' || vm.type=='update'){
            vm.info();
          }
        }).catch(error => {
          vm.$message.error("执行失败！"+error.response.data.error_msg);
        })
      },
      onGetArr(e){
        let vm=this;
        vm.newList.push(e);
        if(e.children){
          for(let i=0; i<e.children.length; i++){
            vm.onGetArr(e.children[i]);
          }
        }
      },
      info(){
        let vm=this;
        infoPlan(vm.id).then(response => {
          let res=response.data;
          vm.areaid=res.area_range;
          vm.$refs.region.setCheckedKeys(res.area_range.split(','));  
          vm.deadline=res.deadline;
          vm.finish_rate=res.finish_rate;
          vm.first_date=res.first_date;
          vm.default_first_date=res.first_date;
          vm.gen_type=res.gen_type;
          vm.plan_cycle=res.plan_cycle;
          vm.plan_title=res.plan_title;
          vm.template_id=res.template_id;
        }).catch(error => {
          vm.$message.error("执行失败！"+error.response.data.error_msg);
        })
      },
      checkedChange(val){
        if(val){
          this.first_date=new Date();
        }else{
          this.first_date=this.default_first_date;
        }
      },
      changeType(val){
        if(val==1){
          this.checked=false;
        }
      },
      showRole(){
        this.roleDataList = [];
        this.newRoleDialogVisible = true;
        this.kw='';
        this.getRoleList();
      },
      getRoleList() {
        let vm = this;
        let params = {
          page_num: 1,
          page_size: 1000
        };
        vm.roleDataListLoading = true;
        getRoleList(params)
        .then( response => {
          let res = response.data;
          vm.roleDataList = res.rows;
          vm.roleDataListLoading = false;
        })
        .catch( error => {
          vm.roleDataListLoading = false;
        })
      },
      setDeptRoleInfo() {
        let checkNode = this.$refs.roleData.getCheckedNodes();
        let roleid = new Array(checkNode.length);
        let rolename= new Array(checkNode.length);
        for (let i = 0; i < checkNode.length; i++) {
          roleid[i] = checkNode[i].role_id;
          rolename[i] = checkNode[i].role_name;
        }
        this.plan_pop=rolename.join(',');
        this.plan_pop_id=roleid.join(',');
        this.newRoleDialogVisible = false;
      },
    }
}
</script>

